package zhihui.mobile.ui.shop.order;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zgm.utils.DateUtils;
import com.zgm.utils.UiUtils;
import com.zgm.utils.ui.UiTextHeader;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import zhihui.mobile.R;
import zhihui.mobile.bean.ilpay.PayResult;
import zhihui.mobile.bean.shop.SkuInfo;
import zhihui.mobile.bean.shop.order.ShopOrder;
import zhihui.mobile.bean.shop.order.ShopOrderDetail;
import zhihui.mobile.bean.wx.WeixinPayInfo;
import zhihui.mobile.config.Config;
import zhihui.mobile.manager.pay.PayManager;
import zhihui.mobile.presenter.IPresenter;
import zhihui.mobile.presenter.shop.ShopOrderDetailPresenter;
import zhihui.mobile.ui.BaseActivity;
import zhihui.mobile.ui.shop.details.ShopDetailsActivity;

/**
 * Created by 张公铭 on 2017/8/15 0015.
 */

public class ShopOrderDetailsActivity extends BaseActivity implements IShopOrderDetailContract.IShopOrderDetailView
{
    private IShopOrderDetailContract.IShopOrderDetailPresenter detailPresenter = new ShopOrderDetailPresenter();

    private UiTextHeader mheader;
    private TextView tv_status;
    private TextView tv_name;
    private TextView tv_phone;
    private TextView tv_address;
    private LinearLayout ll_shops;
    private TextView tv_orderId;
    private TextView tv_time;
    private TextView tv_money;
    private TextView tv_express;
    private TextView tv_sales;
    private TextView tv_pay_money;
    private LinearLayout ll_pay_timeout;
    private TextView tv_timeout;
    private Button btn_one;
    private Button btn_two;
    private RelativeLayout rl_footer;

    private Handler mHander;
    private static final int SDK_PAY_FLAG = 1;
    private IWXAPI api;
    private Timer mTimer;
    private long timeout;
    private final int refresh_time = 10000;

    @Override
    public void initView()
    {
        PayManager.wx_pay = 0;
        api = WXAPIFactory.createWXAPI(this, Config.WX_APP_ID, true);
        api.registerApp(Config.WX_APP_ID);

        mHander = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                switch (msg.what)
                {
                    case SDK_PAY_FLAG:
                    {
                        PayResult payResult = new PayResult((String) msg.obj);
                        /**
                         * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                         * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                         * docType=1) 建议商户依赖异步通知
                         */
                        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                        String resultStatus = payResult.getResultStatus();
                        // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                        if (TextUtils.equals(resultStatus, "9000"))
                        {
                            showMessage("支付成功");
                        } else
                        {
                            // 判断resultStatus 为非"9000"则代表可能支付失败
                            // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                            if (TextUtils.equals(resultStatus, "8000"))
                            {
                                showMessage("支付结果确认中");
                            } else
                            {
                                // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                                showMessage("支付失败");
                            }
                        }
                        break;
                    }
                    case refresh_time:

                        long time = (long) msg.obj;
                        if (time < 0)
                        {
                            tv_status.setText("已取消");
                            hindfooter();
                            mTimer.cancel();
                            mTimer = null;
                        } else
                        {
                            String timestr = "00:";
                            int m = (int) (time / 1000 / 60);
                            if (m >= 10)
                            {
                                timestr += m;
                            } else
                            {
                                timestr += "0" + m;
                            }
                            int s = (int) (time / 1000 % 60);
                            if (s >= 10)
                            {
                                timestr += ":" + s;
                            } else
                            {
                                timestr += ":0" + s;
                            }
                            tv_timeout.setText(timestr);
                        }
                        break;
                    default:
                        break;
                }
            }
        };

        mheader = (UiTextHeader) findViewById(R.id.shop_order_details_header);
        mheader.setTitle("订单详情");
        mheader.setLeftBottonIcon(R.drawable.shop_back);
        mheader.setLeftButtonOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                goBack(ShopOrderDetailsActivity.class);
            }
        });
        mheader.hindRight();

        tv_status = (TextView) findViewById(R.id.tv_shop_order_details_status);
        tv_name = (TextView) findViewById(R.id.tv_shop_order_details_name);
        tv_phone = (TextView) findViewById(R.id.tv_shop_order_details_phone);
        tv_address = (TextView) findViewById(R.id.tv_shop_order_details_address);

        ll_shops = (LinearLayout) findViewById(R.id.ll_shop_order_details_shops);
        tv_orderId = (TextView) findViewById(R.id.tv_shop_order_details_order);
        tv_time = (TextView) findViewById(R.id.tv_shop_order_details_order_time);

        tv_money = (TextView) findViewById(R.id.tv_shop_order_details_count_price);
        tv_express = (TextView) findViewById(R.id.tv_shop_order_details_express);
        tv_sales = (TextView) findViewById(R.id.tv_shop_order_details_sales_price);
        tv_pay_money = (TextView) findViewById(R.id.tv_shop_order_detail_pay_money);


        ll_pay_timeout = (LinearLayout) findViewById(R.id.ll_shop_order_details_times);
        ll_pay_timeout.setVisibility(View.GONE);
        tv_timeout = (TextView) findViewById(R.id.tv_shop_order_details_time_out);

        btn_one = (Button) findViewById(R.id.btn_shop_order_details_one);
        btn_two = (Button) findViewById(R.id.btn_shop_order_details_two);

        rl_footer = (RelativeLayout) findViewById(R.id.rl_shop_order_details_footer);

        detailPresenter.initData();
    }

    @Override
    protected int getLayoutResId()
    {
        return R.layout.shop_order_details_activity;
    }

    @Override
    protected IPresenter[] getPresenters()
    {
        return new IPresenter[]{detailPresenter};
    }

    @Override
    protected void onInitPresenter()
    {
        detailPresenter.init(ShopOrderDetailsActivity.this, ShopOrderDetailsActivity.this);
    }

    @Override
    public void initViewData(final ShopOrderDetail orderDetail)
    {
        if (orderDetail == null)
        {
            showMessage("初始化数据失败！");
            goBack(ShopDetailsActivity.class);
            return;
        }
        tv_status.setText(ShopOrder.getStatus(orderDetail.getStatus()));

        tv_name.setText(orderDetail.getName());
        tv_phone.setText(orderDetail.getTel());
        tv_address.setText(orderDetail.getAddress());

        tv_orderId.setText("订单编号:" + orderDetail.getCode());
        tv_time.setText("下单时间:" + DateUtils.formatTime(orderDetail.getTime()));

        tv_money.setText("￥" + ((double) orderDetail.getMoney() / 100));
        tv_express.setText("￥0");
        tv_sales.setText("￥" + (((double) (orderDetail.getMoney() - orderDetail.getPaymoney())) / 100));
        tv_pay_money.setText("实付款：￥" + ((double) orderDetail.getPaymoney()) / 100);

        List<SkuInfo> list = orderDetail.getGoodsList();
        for (SkuInfo skuInfo : list)
        {
            View view = LayoutInflater.from(this).inflate(R.layout.shop_order_details_item, ll_shops, false);
            ImageView iv_shop_icon = (ImageView) view.findViewById(R.id.iv_shop_order_details_item_img);
            ImageLoader.getInstance().displayImage(Config.FILE_URL + skuInfo.getThumbnail(), iv_shop_icon);
            TextView tv_shop_title = (TextView) view.findViewById(R.id.tv_shop_order_details_item_name);
            tv_shop_title.setText(skuInfo.getTitle());
            TextView tv_shop_specification = (TextView) view.findViewById(R.id.tv_shop_order_details_item_specification);
            tv_shop_specification.setText(skuInfo.getSpecif().replace(",", "  "));
            TextView tv_shop_price = (TextView) view.findViewById(R.id.tv_shop_order_details_item_price);
            tv_shop_price.setText("￥" + ((double) skuInfo.getPrice() / 100));
            TextView tv_shop_num = (TextView) view.findViewById(R.id.tv_shop_order_details_item_num);
            tv_shop_num.setText("×" + skuInfo.getNum());
            ll_shops.addView(view);
        }

        switch (orderDetail.getStatus())
        {
            case 1:         //待付款
                if (orderDetail.getRemainTime() < 0)
                {
                    tv_status.setText("已取消");
                    ll_pay_timeout.setVisibility(View.GONE);
                    hindfooter();
                } else
                {
                    timeout = orderDetail.getRemainTime();
                    ll_pay_timeout.setVisibility(View.VISIBLE);
                    mTimer = new Timer(true);
                    TimerTask timerTask = new TimerTask()
                    {
                        @Override
                        public void run()
                        {
                            timeout -= 1000;
                            Message message = new Message();
                            message.what = refresh_time;
                            message.obj = timeout;
                            mHander.sendMessage(message);
                        }
                    };
                    mTimer.schedule(timerTask, 0, 1000);

                    btn_one.setText("去支付");
                    btn_one.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            zhihui.mobile.ui.utils.UiUtils.showPayDialog(ShopOrderDetailsActivity.this, orderDetail.getPaymoney(), new zhihui.mobile.ui.utils.UiUtils.IPayListener()
                            {
                                @Override
                                public void weixinPay()
                                {
                                    detailPresenter.weixinPay(orderDetail.getOrderId(), orderDetail.getPaymoney());
                                }

                                @Override
                                public void ilPay()
                                {
                                    detailPresenter.alipay(orderDetail.getOrderId(), orderDetail.getPaymoney());
                                }
                            });
                        }
                    });
                    btn_two.setText("取消订单");
                    btn_two.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            detailPresenter.updateOrderStatus(orderDetail.getOrderId(), 5);
                        }
                    });
                }
                break;
            case 2:         //待出库
            case 3:         //待收货
                btn_one.setText("确认收货");
                btn_one.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        detailPresenter.updateOrderStatus(orderDetail.getOrderId(), 4);
                    }
                });

                if ((System.currentTimeMillis() - orderDetail.getTime()) > 7 * 24 * 60 * 60 * 1000)
                {
                    btn_two.setVisibility(View.GONE);
                } else
                {
                    btn_two.setText("退货退款");
                    btn_two.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            //detailPresenter.updateOrderStatus(orderDetail.getOrderId(), 6);
                            UiUtils.showDialog(ShopOrderDetailsActivity.this, "退款提示", ShopOrderDetailsActivity.this.getString(R.string.return_shop));
                        }
                    });
                }
                break;
            case 4:         //已完成
                btn_one.setVisibility(View.GONE);
                if ((System.currentTimeMillis() - orderDetail.getTime()) > 7 * 24 * 60 * 60 * 1000)
                {
                    btn_two.setVisibility(View.GONE);
                } else
                {
                    btn_two.setText("退货退款");
                    btn_two.setOnClickListener(new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            //detailPresenter.updateOrderStatus(orderDetail.getOrderId(), 6);
                            UiUtils.showDialog(ShopOrderDetailsActivity.this, "退款提示", ShopOrderDetailsActivity.this.getString(R.string.return_shop));
                        }
                    });
                }
                break;
            case 5:         //已取消
            case 6:         //退款中
            case 7:         //退款完成
                rl_footer.setVisibility(View.GONE);
                break;
            default:
                rl_footer.setVerticalGravity(View.GONE);
                break;
        }
    }

    @Override
    public void alipay(final String data)
    {
        Runnable payRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(ShopOrderDetailsActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHander.sendMessage(msg);
            }
        };
        Thread thread = new Thread(payRunnable);
        thread.start();
    }

    @Override
    public void weixinPay(WeixinPayInfo payInfo)
    {
        PayReq payRequest = new PayReq();
        payRequest.appId = Config.WX_APP_ID;
        payRequest.partnerId = payInfo.getPartnerid();
        payRequest.prepayId = payInfo.getPrepayid();
        payRequest.packageValue = payInfo.getPackages();
        payRequest.nonceStr = payInfo.getNoncestr();
        payRequest.timeStamp = payInfo.getTimestamp();
        payRequest.sign = payInfo.getSign();

        api.sendReq(payRequest);
    }

    @Override
    public void hindfooter()
    {
        rl_footer.setVisibility(View.GONE);
    }
}
